#include "hex_bin.h"

namespace herm{

HexBin::HexBin()
{
    for (int i = 0; i < BASELENGTH; i++ )
    {
        hexNumberTable[i] = -1;
    }
    for ( int i = '9'; i >= '0'; i--) 
    {
        hexNumberTable[i] = (unsigned char) (i-'0');
    }
    for ( int i = 'F'; i>= 'A'; i--) 
    {
        hexNumberTable[i] = (unsigned char) ( i-'A' + 10 );
    }
    for ( int i = 'f'; i>= 'a'; i--)
    {
        hexNumberTable[i] = (unsigned char) ( i-'a' + 10 );
    }

    for(int i = 0; i<10; i++ ) 
    {
        lookUpHexAlphabet[i] = (char)('0'+i);
    }
    for(int i = 10; i<=15; i++ ) 
    {
        lookUpHexAlphabet[i] = (char)('A'+i -10);
    }
}

/***
* Encode a byte array to hex string
*
* @param binaryData array of byte to encode
* @return return encoded string
*/
std::string HexBin::Encode(const std::string& binaryData) 
{  
    int lengthData   = binaryData.length();
    int lengthEncode = lengthData * 2;

    char* encodedData = new char[lengthEncode];
    int temp;
    for (int i = 0; i < lengthData; i++)
    {
        temp = binaryData[i];
        if (temp < 0)
            temp += 256;
        encodedData[i*2] = lookUpHexAlphabet[temp >> 4];
        encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf];
    }
    
    std::string ret(encodedData, lengthEncode);
    delete encodedData;

    return ret;
}
}